package com.feihe.controller;

import com.feihe.dto.*;
import com.feihe.service.AdminService;
import com.feihe.service.EncryptionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin")
public class AdminController {
    
    @Autowired
    private AdminService adminService;
    
    @Autowired
    private EncryptionService encryptionService;
    
    /**
     * 管理员登录
     */
    @PostMapping("/login")
    public ApiResponse<Void> login(@RequestBody Map<String, Object> requestBody, HttpSession session) {
        try {
            // 解密请求（如果需要）
            String decryptedData = encryptionService.decryptRequestIfNeeded(requestBody);
            
            // 解析登录请求
            AdminLoginRequest request = encryptionService.parseDecryptedData(decryptedData, AdminLoginRequest.class);
            
            // 执行登录验证
            boolean success = adminService.login(request.getUsername(), request.getPassword());
            
            if (success) {
                // 登录成功，保存session
                session.setAttribute("admin_username", request.getUsername());
            }
            
            return ApiResponse.success();
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 管理员登出
     */
    @PostMapping("/logout")
    public ApiResponse<Void> logout(HttpSession session) {
        try {
            session.removeAttribute("admin_username");
            session.invalidate();
            return ApiResponse.success();
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 检查登录状态
     */
    @GetMapping("/check_login")
    public ApiResponse<Map<String, Object>> checkLogin(HttpSession session) {
        try {
            String username = (String) session.getAttribute("admin_username");
            Map<String, Object> result = new java.util.HashMap<>();
            result.put("isLoggedIn", username != null);
            result.put("username", username);
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 添加日历状态
     */
    @PostMapping("/calendar/status")
    public ApiResponse<Void> addCalendarStatus(@RequestBody Map<String, Object> requestBody, HttpSession session) {
        try {
            // 检查登录状态
            if (!isAdminLoggedIn(session)) {
                return ApiResponse.error("请先登录");
            }
            
            // 解密请求（如果需要）
            String decryptedData = encryptionService.decryptRequestIfNeeded(requestBody);
            
            // 解析请求
            CalendarStatusRequest request = encryptionService.parseDecryptedData(decryptedData, CalendarStatusRequest.class);
            
            // 执行添加操作
            adminService.addCalendarStatus(request.getStatus(), request.getCalendarStartTime(), request.getCalendarEndTime());
            
            return ApiResponse.success();
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 删除预约
     */
    @DeleteMapping("/reservations/{id}")
    public ApiResponse<Void> deleteReservation(@PathVariable Long id, HttpSession session) {
        try {
            // 检查登录状态
            if (!isAdminLoggedIn(session)) {
                return ApiResponse.error("请先登录");
            }
            
            // 执行删除操作
            adminService.deleteReservation(id);
            
            return ApiResponse.success();
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 通过POST方式删除预约（兼容原PHP接口）
     */
    @PostMapping("/reservations/delete")
    public ApiResponse<Void> deleteReservationPost(@RequestBody Map<String, Object> requestBody, HttpSession session) {
        try {
            // 检查登录状态
            if (!isAdminLoggedIn(session)) {
                return ApiResponse.error("请先登录");
            }
            
            // 解密请求（如果需要）
            String decryptedData = encryptionService.decryptRequestIfNeeded(requestBody);
            
            // 提取ID
            Object idObj = encryptionService.extractField(decryptedData, "id");
            Long id = null;
            
            if (idObj instanceof Integer) {
                id = ((Integer) idObj).longValue();
            } else if (idObj instanceof Long) {
                id = (Long) idObj;
            } else if (idObj instanceof String) {
                id = Long.parseLong((String) idObj);
            }
            
            if (id == null) {
                return ApiResponse.error("预约ID不能为空");
            }
            
            // 执行删除操作
            adminService.deleteReservation(id);
            
            return ApiResponse.success();
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 查询预约和日历数据
     */
    @PostMapping("/query")
    public ApiResponse<List<Map<String, Object>>> queryData(@RequestBody Map<String, Object> requestBody, HttpSession session) {
        try {
            // 检查登录状态
            if (!isAdminLoggedIn(session)) {
                return ApiResponse.error("请先登录");
            }
            
            // 解密请求（如果需要）
            String decryptedData = encryptionService.decryptRequestIfNeeded(requestBody);
            
            // 解析请求
            AdminQueryRequest request = encryptionService.parseDecryptedData(decryptedData, AdminQueryRequest.class);
            
            // 执行查询
            List<Map<String, Object>> result = adminService.queryReservationsAndCalendars(request);
            
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 获取预约列表（支持过滤）
     */
    @GetMapping("/reservations")
    public ApiResponse<List<Map<String, Object>>> getReservations(
            @RequestParam(required = false) String date,
            @RequestParam(required = false) String search,
            @RequestParam(required = false) Integer type,
            HttpSession session) {
        try {
            // 检查登录状态
            if (!isAdminLoggedIn(session)) {
                return ApiResponse.error("请先登录");
            }
            
            // 获取过滤后的预约列表
            List<Map<String, Object>> reservations = adminService.getFilteredReservations(date, search, type);
            
            return ApiResponse.success(reservations);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 获取预约列表HTML（list.html专用）
     */
    @PostMapping("/query/list")
    public ApiResponse<Map<String, Object>> getReservationListHtml(
            @RequestBody Map<String, Object> requestBody,
            HttpSession session) {
        try {
            // 检查登录状态
            if (!isAdminLoggedIn(session)) {
                return ApiResponse.error("请先登录");
            }
            
            // 解密请求（如果需要）
            String decryptedData = encryptionService.decryptRequestIfNeeded(requestBody);
            Map<String, Object> params = encryptionService.parseDecryptedData(decryptedData, Map.class);
            
            String search = (String) params.get("search");
            String rili = (String) params.get("rili");
            String typeStr = (String) params.get("type");
            Integer type = (typeStr != null && !typeStr.trim().isEmpty()) ? Integer.parseInt(typeStr) : null;
            
            // 获取过滤后的预约列表
            List<Map<String, Object>> reservations = adminService.getFilteredReservations(rili, search, type);
            
            // 生成HTML片段
            StringBuilder html = new StringBuilder();
            for (Map<String, Object> reservation : reservations) {
                html.append(generateReservationHtml(reservation));
            }
            
            // 返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("html", html.toString());
            result.put("count", reservations.size());
            
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 生成预约记录的HTML片段
     */
    private String generateReservationHtml(Map<String, Object> reservation) {
        String typeName = getTypeName((Integer) reservation.get("type"));
        String checkStatus = (Integer) reservation.get("is_check") == 1 ? "已签到" : "未签到";
        String startTime = formatDateTime(reservation.get("reservation_start_time"));
        
        return String.format(
            "<div style=\"border:1px solid #EFEFEF;border-radius:6px;width:100%%;height:60px;margin-bottom:20px;background:#ffffff;display:flex;align-items: center;font-size:14px;\">" +
            "<div style=\"flex:1;text-align:center;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;\">%s</div>" +
            "<div style=\"flex:1;text-align:center;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;\">%s</div>" +
            "<div style=\"flex:1;text-align:center;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;\">场地%s</div>" +
            "<div style=\"flex:1;text-align:center;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;\">%s人</div>" +
            "<div style=\"flex:1;text-align:center;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;\">%s</div>" +
            "<div style=\"flex:1;text-align:center;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;\">%s</div>" +
            "<div style=\"flex:1;text-align:center;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;\">%s</div>" +
            "<div style=\"flex:1;text-align:center;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;\">" +
            "<button onclick=\"cli_delete_reservation(%s)\" style=\"background:#f44336;color:#fff;border:none;border-radius:4px;padding:6px 12px;cursor:pointer;margin:0 10px;\">删除</button>" +
            "</div>" +
            "</div>",
            reservation.get("realname") != null ? reservation.get("realname") : "",
            reservation.get("telephone") != null ? reservation.get("telephone") : "",
            reservation.get("ground") != null ? reservation.get("ground") : "",
            reservation.get("visitor_number") != null ? reservation.get("visitor_number") : "",
            typeName,
            startTime,
            checkStatus,
            reservation.get("id")
        );
    }
    
    /**
     * 获取类型名称
     */
    private String getTypeName(Integer type) {
        if (type == null) return "";
        switch (type) {
            case 1: return "内部学习/培训备份";
            case 2: return "产品/品牌体验备份";
            case 3: return "公众参观/科普教育备份";
            case 4: return "商业邀约/参观备份";
            case 5: return "社会团体/学术交流备份";
            case 6: return "VIP/定向邀约备份";
            case 7: return "政府考察/调研备份";
            case 8: return "媒体/机构备份";
            case 9: return "其他";
            default: return "";
        }
    }
    
    /**
     * 格式化日期时间
     */
    private String formatDateTime(Object dateTime) {
        if (dateTime == null) return "";
        try {
            if (dateTime instanceof LocalDateTime) {
                LocalDateTime ldt = (LocalDateTime) dateTime;
                return String.format("%04d-%02d-%02d %02d:%02d",
                    ldt.getYear(), ldt.getMonthValue(), ldt.getDayOfMonth(),
                    ldt.getHour(), ldt.getMinute());
            }
        } catch (Exception e) {
            // 格式化失败，返回空字符串
        }
        return "";
    }

    /**
     * 检查管理员是否已登录
     */
    private boolean isAdminLoggedIn(HttpSession session) {
        String username = (String) session.getAttribute("admin_username");
        return username != null && !username.trim().isEmpty();
    }
} 